package org.example.gateway.event.listener;

import com.google.common.collect.Lists;
import org.example.gateway.enums.OperationTypeEnum;
import org.example.gateway.event.RuleAddEvent;
import org.example.gateway.event.RuleDeleteEvent;
import org.example.gateway.pojo.dto.AppRuleDto;
import org.example.gateway.pojo.dto.RouteRuleOperationDto;
import org.example.gateway.sync.WebSocketSyncCacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RuleEventListener {
    @Autowired
    private WebSocketSyncCacheClient client;

    @EventListener
    private void onAdd(RuleAddEvent event) {
        RouteRuleOperationDto operation = new RouteRuleOperationDto(OperationTypeEnum.INSERT, Lists.newArrayList(event.getAppRuleDto()));
        client.send(operation);
    }

    @EventListener
    public void onDelete(RuleDeleteEvent ruleDeleteEvent) {
        List<AppRuleDto> list = Lists.newArrayList(ruleDeleteEvent.getAppRuleDto());
        RouteRuleOperationDto operationDTO = new RouteRuleOperationDto(OperationTypeEnum.DELETE, list);
        client.send(operationDTO);
    }
}
